package com.chinafree.business.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.chinafree.business.mapping.UserMapping;
import com.chinafree.business.model.enumeration.PositionTypeEnum;
import com.chinafree.business.model.result.Industry;
import com.chinafree.business.model.result.PositionResult;
import com.chinafree.business.model.result.ProvCityResult;
import com.chinafree.business.model.result.UserBaseMessageResult;
import com.chinafree.business.service.CommonService;
import com.chinafree.business.service.PDFService;
import com.chinafree.business.service.ResumeService;
import com.chinafree.business.service.UserService;
import com.chinafree.common.model.enumeration.ResponseCodeEnum;
import com.chinafree.common.model.response.EntityResponse;
import com.chinafree.common.utils.QiniuUtils;
import com.chinafree.mapper.MaUserDeliveryMapper;
import com.chinafree.model.po.FndPosition;
import com.chinafree.model.po.FndProvCityArea;
import com.chinafree.model.po.MaUserDelivery;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CommonServiceImpl extends BaseServiceImpl implements CommonService  {

    @Autowired
    private PDFService pdfService;

    @Autowired
    private ResumeService resumeService;

    @Autowired
    private UserService userService;

    @Autowired
    private MaUserDeliveryMapper maUserDeliveryMapper;

    @Override
    public EntityResponse<List<ProvCityResult>> getProvinceResult() {
        List<FndProvCityArea> fndProvCityAreas = userService.getCityAll();
        List<ProvCityResult> provCityResults = UserMapping.instance.fndProvCityAreaToProvCityResult(fndProvCityAreas);
        Map<String, ProvCityResult> map = provCityResults.stream()
                .collect(Collectors.toMap(ProvCityResult::getValue, Function.identity(), (o1, o2) -> o1));
        map.put("0", new ProvCityResult());
        for (ProvCityResult p : provCityResults) {
            String pid = p.getParentId();
            if (map.containsKey(pid)) {
                if (CollectionUtils.isEmpty(map.get(pid).getChildren())) {
                    List<ProvCityResult> children = new ArrayList<>();
                    children.add(p);
                    map.get(pid).setChildren(children);
                } else {
                    map.get(pid).getChildren().add(p);
                }
            }
        }
        List<ProvCityResult> provinceResults = map.get("0").getChildren();
        return new EntityResponse<>(ResponseCodeEnum.SUCCESS, "查询成功", provinceResults);
    }

    @Override
    public List<Industry> getIndustry() {
        List<Industry> list = new ArrayList<Industry>();
        for (PositionTypeEnum p : PositionTypeEnum.values()) {
            list.add(new Industry(p.getId(), p.getType()));
        }
        return list;
    }

    @Override
    public EntityResponse<List<PositionResult>> getPositionResult() {
        List<FndPosition> fndPositions = userService.getJobTypeAll();
        HashMap<Integer, List<PositionResult.PositionSubResult>> map = new HashMap<>();
        for (FndPosition f : fndPositions) {
            map.computeIfAbsent(f.getType(), ArrayList::new);
            map.get(f.getType()).add(new PositionResult.PositionSubResult(f.getId(), f.getPositionName()));
        }
        List<PositionResult> positionResults = new ArrayList<>();
        for (PositionTypeEnum positionTypeEnum : PositionTypeEnum.values()) {
            PositionResult positionResult = new PositionResult();
            positionResult.setValue(positionTypeEnum.getId());
            positionResult.setLabel(positionTypeEnum.getType());
            if (map.containsKey(positionTypeEnum.getId())) {
                positionResult.setChildren(map.get(positionTypeEnum.getId()));
            }
            positionResults.add(positionResult);
        }
        return new EntityResponse<>(ResponseCodeEnum.SUCCESS, "查询成功", positionResults);
    }

    @Value("${sava_path_pic}")
    private String savaPath;

    @Override
    public EntityResponse<String> uploadPic(MultipartFile file, String uploadDir, HttpServletRequest request)
            throws Exception {
        if (file != null) {// 判断上传的文件是否为空
            String fileName = file.getOriginalFilename();// 文件原名称
            log.info("上传的文件原名称:{}", fileName);
            // 判断文件类型
            String type = fileName.indexOf(".") != -1
                    ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length())
                    : null;
            if (type != null) {// 判断文件类型是否为空
                if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase())
                        || "JPG".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                    UUID uuid = UUID.randomUUID();
                    String name = uuid + "_" + fileName;
                    // file.get
                    byte[] fileBytes = file.getBytes();
                    return new EntityResponse<>(ResponseCodeEnum.SUCCESS, "文件成功上传到指定目录下", fileBytes.toString());
                }
            } else {
                return EntityResponse.failure("不是我们想要的文件类型,请按要求重新上传");
            }
        } else {
            return EntityResponse.failure("文件类型为空");
        }
        return EntityResponse.failure("已经成功上传到指定目录");
    }

    @Override
    public void exportResume(Long userId, HttpServletResponse response) {
        UUID uuid = UUID.randomUUID();
        MaUserDelivery ma = new MaUserDelivery();
        ma.setExport(1);
        // userService.updateUserDelivery(userId, getCompanyId() ,ma);
        EntityResponse<UserBaseMessageResult> byUserId = resumeService.getByUserId(userId);
        if (byUserId.getCode() != 200) {
            return;
        }
        UserBaseMessageResult responseData = byUserId.getResponseData();
        String filename = savaPath + "/" + responseData.getBaseUserResult().getFirstname() + "_"
                + responseData.getBaseUserResult().getLastname() + ".pdf";
        try {
            pdfService.createPDF(filename, responseData);
            downloadFile(response, filename);
        } catch (Exception e) {
            throw new RuntimeException("创建pdf异常:{}", e);

        }
    }

    // @Override
    public EntityResponse<MultipartFile> downloadPic(String path) {
        // FileInputStream fileInputStream = null;
        // MultipartFile multipartFile = null;
        // try {
        // MultipartFile multipartFile1 = new MultipartFile(path);
        // } catch (Exception e) {
        // e.printStackTrace();
        // }
        // return multipartFile;
        return null;
    }

    // @Override
    public void downloadFile(HttpServletResponse response, String path) {
        try {
            // path: 欲下载的文件的路径
            File file = new File(path);
            // 获取文件名 - 设置字符集
            String downloadFileName = new String(file.getName().getBytes(StandardCharsets.UTF_8), "iso-8859-1");
            // 以流的形式下载文件
            InputStream fis;
            fis = new BufferedInputStream(new FileInputStream(path));

            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}